import 'package:flutter/material.dart';

enum ToastPosition { top, center, bottom }

class Toast {
  static OverlayEntry _overlayEntry;
  static bool _showing = false;
  static ToastPosition toastPosition;
  static DateTime _startTime;
  static String _msg;
  static void show(
    BuildContext context, {
    String msg,
    int duration = 1,
    ToastPosition toastPosition,
    Color background = const Color(0x73242424),
    TextStyle textStyle = const TextStyle(
      fontSize: 15,
      color: Colors.white,
      backgroundColor: Colors.transparent,
    ),
    double backgroundRadius = 2,
    Border border,
  }) async {
    OverlayState overlayState = Overlay.of(context);
    toastPosition = ToastPosition.center;
    _startTime = DateTime.now();
    _showing = true;
    _msg = msg;
    if (_overlayEntry == null) {
      _overlayEntry = OverlayEntry(
        builder: (BuildContext context) => ToastWidget(
          widget: Container(
            width: MediaQuery.of(context).size.width,
            child: Container(
              alignment: Alignment.center,
              width: MediaQuery.of(context).size.width,
              child: Container(
                decoration: BoxDecoration(
                  color: background,
                  borderRadius: BorderRadius.circular(backgroundRadius),
                  border: border,
                ),
                margin: EdgeInsets.symmetric(horizontal: 20),
                padding: EdgeInsets.symmetric(vertical: 5, horizontal: 20),
                child: Text(_msg, softWrap: true, style: textStyle),
              ),
            ),
          ),
          toastPosition: toastPosition,
        ),
      );
      overlayState.insert(_overlayEntry);
    } else {
      //重新绘制UI，类似setState
      _overlayEntry.markNeedsBuild();
    }
    await Future.delayed(Duration(seconds: duration));
    if (DateTime.now().difference(_startTime).inSeconds >= duration) {
      // 如果当前时间与toast显示的开始时间差大于等于显示时间就消失 否则继续显示
      dismiss();
    }
  }

  static dismiss() async {
    if (!_showing) return;
    _showing = false;
    _overlayEntry?.remove();
    _overlayEntry = null;
  }
}

class ToastWidget extends StatelessWidget {
  ToastWidget({Key key, @required this.widget, this.toastPosition})
      : super(key: key);

  final Widget widget;
  final ToastPosition toastPosition;

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: buildToastPosition(context),
      child: Material(
        color: Colors.transparent,
        child: widget,
      ),
    );
  }

  double buildToastPosition(context) {
    var top;
    if (toastPosition == ToastPosition.top) {
      top = MediaQuery.of(context).size.height * 1 / 4;
    } else if (toastPosition == ToastPosition.center) {
      top = MediaQuery.of(context).size.height * 2 / 5;
    } else {
      top = MediaQuery.of(context).size.height * 3 / 4;
    }
    return top;
  }
}
